package com.example.myproject.web;

import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * Created by xi on 2018/6/23.
 */
@Controller
public class TestThreadController {

    private List<ExecutorService> list = new ArrayList<ExecutorService>();

    @RequestMapping(value={"/testThread"}, method= RequestMethod.GET)
    public void testThread(){
        for(int j=0;j<2000;j++){
            ExecutorService singleThreadExecutor = Executors.newCachedThreadPool();
            for (int i = 0; i < 1000; i++) {
                final int index = i;
                singleThreadExecutor.execute(new Runnable() {
                    public void run() {
                        try {
                            System.out.println(index);
                            Thread.sleep( Integer.MAX_VALUE);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
                list.add(singleThreadExecutor);
            }
        }
    }
    public static Executor poolExecutor;

    @Bean
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数
        poolTaskExecutor.setCorePoolSize(1);
        // 线程池维护线程的最大数量,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        poolTaskExecutor.setMaxPoolSize(1);
        // 缓存队列大小
        poolTaskExecutor.setQueueCapacity(Integer.MAX_VALUE);
        // 允许的空闲时间,当超过了核心线程之外的线程在空闲时间到达之后会被销毁
        poolTaskExecutor.setKeepAliveSeconds(20000);
        // 指定用于新创建的线程名称的前缀。
        poolTaskExecutor.setThreadNamePrefix("aaa");
        // 指定任务被拒绝时执行的策略，ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
        //poolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        poolTaskExecutor.initialize();
        poolExecutor = poolTaskExecutor;
        return poolTaskExecutor;
    }

    @RequestMapping(value={"/testFutaskMemo"}, method= RequestMethod.GET)
    public void testFutaskMemo(){
        for(int j=0;j<1000;j++){
            for (int i = 0; i < 1000; i++) {
                final int index = i;
                poolExecutor.execute(()->{
                    try {
                        Thread.sleep(1000 * 60 * 60);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
        }

    }
}
